package net.xdclass.component;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.SmsConfig;
import net.xdclass.util.CommonUtil;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


@Component
@Slf4j
public class SmsComponent {

    private static final String urlTemplate = "https://mysms.market.alicloudapi.com/sms?mobile=%s&content=%s";


    @Autowired
    private SmsConfig smsConfig;

    @Autowired
    private RestTemplate restTemplate;


    @Async("threadPoolTaskExecutor")
    public void send(String to, String context) {
        String url = String.format(urlTemplate, to, context);
        HttpHeaders headers = new HttpHeaders();
                headers.set("Authorization", "APPCODE " + smsConfig.getAppCode());
        HttpEntity<String> entity = new HttpEntity<>(headers);
        long start = CommonUtil.getCurrentTimestamp();
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity,
                        String.class);
        long end = CommonUtil.getCurrentTimestamp();
        log.info("耗时:{}--------url={},body={}",end-start, url, response.getBody());

        if (response.getStatusCode() ==
                HttpStatus.OK) {
            log.info("发送短信成功,响应信息:{}", response.getBody());
        } else {
            log.error("发送短信失败,响应信息:{}", response.getBody());
        }
    }
}

